package com.cskaoyan.service.admin;

import com.cskaoyan.bean.*;
import com.cskaoyan.config.realm.MarketToken;
import com.cskaoyan.mapper.MarketAdminMapper;
import com.cskaoyan.mapper.MarketModuleAuthMapper;
import com.cskaoyan.mapper.MarketPermissionMapper;
import com.cskaoyan.mapper.MarketRoleMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    MarketPermissionMapper marketPermissionMapper;

    @Autowired
    MarketAdminMapper marketAdminMapper;

    @Autowired
    MarketRoleMapper marketRoleMapper;

    @Autowired
    MarketModuleAuthMapper marketModuleAuthMapper;

    @Override
    @Transactional
    public LoginUserData login(String username, String password) {
        //在这里要执行登录，Subject.login
        // → Subject只能作为局部变量，不能作为全局变量
        Subject subject = SecurityUtils.getSubject();
        // 执行登录（认证）
        //UsernamePasswordToken authenticationToken = new UsernamePasswordToken(username,password);
        MarketToken authenticationToken = new MarketToken(username, password, "admin");
        try {
            // realm.doGetAuthenticationInfo
            subject.login(authenticationToken);
        } catch (AuthenticationException e) {
            e.printStackTrace();
        }

        // 判断是否认证成功
        boolean authenticated = subject.isAuthenticated();
        if(!authenticated){//认证失败
            return null;
        }

        //认证成功

        // 可以获得session信息，也可以获得其sessionId
        Session session = subject.getSession();

        // 获得Principal信息 → realm的doGetAuthorizationInfo方法构造的认证信息里的第一个参数
        MarketAdmin primaryPrincipal = (MarketAdmin) subject.getPrincipals().getPrimaryPrincipal();
        LoginUserData loginUserData = new LoginUserData();
        AdminInfoBean adminInfo = new AdminInfoBean();

        //准备返回管理员信息
        adminInfo.setAvatar(primaryPrincipal.getAvatar());
        adminInfo.setNickName(primaryPrincipal.getUsername());
        loginUserData.setAdminInfo(adminInfo);
        loginUserData.setToken((String) session.getId());






//        adminInfo.setAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
//        adminInfo.setNickName("admin123");
//        loginUserData.setAdminInfo(adminInfo);
//        //loginUserData.setToken("c4d988f3-e4c5-4e46-b6ce-13b9e008ea20");
//        loginUserData.setToken((String) session.getId());
//        //响应sessionId信息给到前端，前端发送请求的时候，通过请求头携带了session的id信息




        //查询所有权限


        //loginUserData.setToken("c4d988f3-e4c5-4e46-b6ce-13b9e008ea20");

        return loginUserData;

    }

    @Override
    public InfoData getInfo(String token) {
        InfoData infoData = new InfoData();
        Subject subject = SecurityUtils.getSubject();
        ArrayList<String> roles = new ArrayList<>();
        ArrayList<String> perms = new ArrayList<>();
        if(subject.isAuthenticated()){
            MarketAdmin primaryPrincipal = (MarketAdmin) subject.getPrincipal();
            //姓名与头像
            infoData.setName(primaryPrincipal.getUsername());
            infoData.setAvatar(primaryPrincipal.getAvatar());
            //获取管理员角色ids
            Integer[] roleIds = primaryPrincipal.getRoleIds();
            //查询所有角色与权限


            for (Integer roleId : roleIds) {
                MarketPermissionExample example = new MarketPermissionExample();
                example.createCriteria().andRoleIdEqualTo(roleId);
                List<MarketPermission> marketPermissions = marketPermissionMapper.selectByExample(example);
                for (MarketPermission marketPermission : marketPermissions) {
                    //权限
                    MarketModuleAuthExample marketModuleAuthExample = new MarketModuleAuthExample();
                    MarketModuleAuthExample.Criteria criteria = marketModuleAuthExample.createCriteria();
                    criteria.andNameEqualTo(marketPermission.getPermission());
                    List<MarketModuleAuth> moduleAuths = marketModuleAuthMapper.selectByExample(marketModuleAuthExample);
                    for (MarketModuleAuth moduleAuth : moduleAuths) {
                        perms.add(moduleAuth.getApi());
                    }
                }
                MarketRole marketRole = marketRoleMapper.selectByPrimaryKey(roleId);
                //角色
                roles.add(marketRole.getName());
            }

            infoData.setRoles(roles);
            infoData.setPerms(perms);
        }


//        infoData.setName("admin123");
//        //根据primaryPrincipal做查询
//        infoData.setAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
//        ArrayList<String> roles = new ArrayList<>();
//        roles.add("超级管理员");
//        infoData.setRoles(roles);
//        ArrayList<String> perms = new ArrayList<>();
//        perms.add("*");
//        infoData.setPerms(perms);
        return infoData;
    }


}
